#include "animatednotifications.h"

animatedNotifications::animatedNotifications(QObject *parent) :
    QObject(parent)
{
    margin = 8;
    signalMapper = new QSignalMapper(this);
    connect(signalMapper, SIGNAL(mapped(int)),
                 this, SLOT(removeNotify(int)));
}

int animatedNotifications::addNotification(QString title, QString msg, QString imagePath)
{
    animatedWidget *wgt;
    wgt = new animatedWidget();

    wgt->setMessage(title, msg, imagePath);

    if (notifications.count()==0)
    {
        QRect geom = QApplication::desktop()->availableGeometry();
        QPoint pnt = geom.bottomRight();
//        pnt.setX(pnt.x()-margin-wgt->geometry().width());
        pnt.setY(pnt.y()-margin-wgt->geometry().height());
        qDebug() << pnt.x() << "x" << pnt.y();
        wgt->topLeft = pnt;
    }
    else
    {
        QPoint pnt = notifications.last()->topLeft;
        pnt.setY(pnt.y()-margin-wgt->geometry().height());
        qDebug() << pnt.x() << "x" << pnt.y();
        wgt->topLeft = pnt;
    }

//    wgt->setMessage(title, msg, imagePath);
    wgt->setAnimation();

    connect(wgt, SIGNAL(finished()), signalMapper, SLOT(map()));
    connect(wgt, SIGNAL(updated()), this, SLOT(updateNotifications()));

    notifications.append(wgt);

    signalMapper->setMapping(wgt, notifications.indexOf(wgt));
    qDebug() << "create notify " << notifications.indexOf(wgt);

    return notifications.indexOf(wgt);
}

int animatedNotifications::removeNotification(int num)
{
    notifications.at(num)->hideMe();
    return 0;
}

int animatedNotifications::removeNotify(int num)
{
    qDebug() << "remove notify " << num;
    notifications.removeAt(num);
    updateNotifications();
    return 0;
}

int animatedNotifications::updateNotifications()
{
    for(int i=0; i<notifications.count();i++)
    {
        qDebug() << "update notify " << i;

        if (i==0)
        {
            QRect geom = QApplication::desktop()->availableGeometry();
            QPoint pnt = geom.bottomRight();
            pnt.setY(pnt.y()-margin-notifications.at(i)->geometry().height());
            qDebug() << pnt.x() << "x" << pnt.y();
            notifications.at(i)->topLeft = pnt;

        }
        else
        {
            QPoint pnt = notifications.at(i-1)->topLeft;
            pnt.setY(pnt.y()-margin-notifications.at(i)->geometry().height());
            qDebug() << pnt.x() << "x" << pnt.y();
            notifications.at(i)->topLeft = pnt;
        }

        signalMapper->setMapping(notifications.at(i), i);
        notifications.at(i)->updateState();
    }
    return 0;
}

void animatedNotifications::test()
{
    for(int i=0; i<notifications.count();i++)
    {
        qDebug() << "update notify " << i;
        notifications.at(i)->topLeft.ry() = notifications.at(i)->topLeft.ry() - 100;
        notifications.at(i)->updateState();
    }
}
